#include "BasePlayer.h"
#include "BtOgrePG.h"
#include "BtOgreGP.h"
#include "BtOgreExtras.h"

using namespace Ogre;


BasePlayer::BasePlayer(Ogre::String name, PlayerNumber pNumber, Ogre::ColourValue pColour, Ogre::Vector3 pPos, Ogre::SceneManager* sceneMgr)
{
	int size = 2.6;

	m_PlayerNumber = pNumber;

	m_pSceneMgr = sceneMgr;

	m_MoveSpeed = 3;

	m_PlayerCube = new DefaultRectangle("SimpleCubeO1", Ogre::Vector3(size, size, size), pColour);
	m_PlayerCube->setCastShadows(true);

	MeshPtr mesh;
	mesh = m_PlayerCube->convertToMesh("CubeMesh" + name);
	mesh->buildEdgeList();
    mesh->prepareForShadowVolume();

	m_PlayerEntity =  m_pSceneMgr->createEntity(name, "CubeMesh" + name);
	m_PlayerNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();

	//m_PlayerNode = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(name);
	//m_PlayerNode->attachObject(m_PlayerCube);

	m_PlayerNode->attachObject(m_PlayerEntity);
    m_PlayerNode->setPosition(pPos);

	m_TranslateVector = Vector3::ZERO;

	 //Create shape.
	BtOgre::StaticMeshToShapeConverter converter(m_PlayerEntity);
    m_PlayerShape = converter.createConvex();

    //Calculate inertia.
    btScalar mass = 5;
    btVector3 inertia;
    m_PlayerShape->calculateLocalInertia(mass, inertia);

    //Create BtOgre MotionState (connects Ogre and Bullet).
    playerState = new BtOgre::RigidBodyState(m_PlayerNode);

    //Create the Body.
    m_PlayerBody = new btRigidBody(mass, playerState, m_PlayerShape, inertia);
}


BasePlayer::~BasePlayer(void)
{
}

void BasePlayer::updatePlayer(double timeSinceLastFrame)
{
	m_MoveScale = m_MoveSpeed  * timeSinceLastFrame;
    m_RotScale  = m_RotateSpeed * timeSinceLastFrame;
	

	m_PlayerBody->clearForces();
	m_PlayerBody->setDamping(0.2, 0.2);
	Ogre::Vector3 UserForce = m_TranslateVector;

	m_PlayerBody->setActivationState(DISABLE_DEACTIVATION);
	m_PlayerBody->applyForce(btVector3(UserForce.x,UserForce.y,UserForce.z),btVector3(0,0,0));

	playerState->setWorldTransform(m_PlayerBody->getWorldTransform());
	m_TranslateVector = Vector3::ZERO;
}

void BasePlayer::moveLeft()
{
	m_TranslateVector.x = -m_MoveScale;
}
void BasePlayer::moveRight()
{
	 m_TranslateVector.x = m_MoveScale;
}
void BasePlayer::moveDown()
{
	m_TranslateVector.z = m_MoveScale;
}
void BasePlayer::moveUp()
{
	m_TranslateVector.z = -m_MoveScale;
}
void BasePlayer::jump()
{
	m_TranslateVector.y = (m_MoveScale * 3);
}